package com.wisdom.system.service.impl.sys;


import com.github.pagehelper.Page;
import com.wisdom.system.dao.sys.SysMenuMapper;
import com.wisdom.system.dao.sys.SysRoleMenuAuthMapper;
import com.wisdom.system.entity.sys.SysMenu;
import com.wisdom.system.entity.base.PageRequest;
import com.wisdom.system.entity.base.PageResult;
import com.wisdom.system.entity.sys.SysMenuTree;
import com.wisdom.system.entity.sys.SysRoleMenuAuth;
import com.wisdom.system.common.exception.LogicException;
import com.wisdom.system.common.mybatis.PageUtil;
import com.wisdom.system.common.mybatis.SqlUtil;
import com.wisdom.system.service.sys.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleMenuAuthMapper sysRoleMenuAuthMapper;

    @Override
    public int addSysMenuInfo(SysMenu sysMenu) {
        sysMenu.setAddTime(new Date());
        return sysMenuMapper.insert(sysMenu);
    }

    @Override
    public int updateSysMenuInfo(SysMenu sysMenu) {
        return sysMenuMapper.updateByPrimaryKeySelective(sysMenu);
    }

    @Override
    @Transactional
    public int delSysMenuInfo(String id) {
        Example example = new Example(SysMenu.class);
        example.createCriteria().andEqualTo("pid",id);
        List<SysMenu> sysMenus = sysMenuMapper.selectByExample(example);
        if (sysMenus.size() >= 1){
            throw LogicException.of("该菜单拥有子级菜单，请先删除子级菜单！");
        }
        //需要同时删除关联表
        Example example1 = new Example(SysRoleMenuAuth.class);
        example1.createCriteria().andEqualTo("fkMenuId",id);
        sysRoleMenuAuthMapper.deleteByExample(example1);
        return sysMenuMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public int delSysMenuList(String ids) {
        String[] idArray = ids.split(",");
        Example example = new Example(SysMenu.class);
        example.createCriteria().andIn("id", Arrays.asList(idArray));
        //需要同时删除关联表
        Example example1 = new Example(SysRoleMenuAuth.class);
        example1.createCriteria().andIn("fkMenuId",Arrays.asList(idArray));
        sysRoleMenuAuthMapper.deleteByExample(example1);
        return sysMenuMapper.deleteByExample(example);
    }

    @Override
    public SysMenu getSysMenuInfo(String id) {
        return sysMenuMapper.getSysMenuInfo(id);
    }

    @Override
    public List<SysMenu> getSysMenuList(String keyword, String fkSystem) {
        return sysMenuMapper.getSysMenuList(SqlUtil.likeEscapeH(keyword), fkSystem);
    }

    @Override
    public PageResult<SysMenu> getSysMenuPageList(String keyword,String fkSystem, PageRequest pageRequest) {
        Page<?> page = PageUtil.startPageAllowNull(pageRequest.getPageNum(), pageRequest.getPageSize());
        return new PageResult<>(getSysMenuList(keyword, fkSystem), page.getTotal());
    }

    @Override
    public int updateSysMenuState(String id, int state) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", id);
        hashMap.put("state", state);
        return sysMenuMapper.updateSysMenuState(hashMap);
    }

    private List<SysMenu> getUserSysMenuList(String fkUserId, String fkSystem, String state) {
        return sysMenuMapper.getUserSysMenuList(fkUserId, fkSystem, state);
    }

    @Override
    public PageResult<SysMenu> getUserSysMenuPageList(String fkUserId, String fkSystem,String state,PageRequest pageRequest) {
        Page<?> page = PageUtil.startPageAllowNull(pageRequest.getPageNum(), pageRequest.getPageSize());
        return new PageResult<>(getUserSysMenuList(fkUserId, fkSystem, state), page.getTotal());
    }

    /**
     * 根据用户ID获取权限菜单树
     * @param fkUserId
     * @param fkSystem
     * @return
     */
    @Override
    public List<SysMenuTree> getUserSysMenuTree(String fkUserId, String fkSystem){
        List<SysMenu> list = getUserSysMenuList(fkUserId, fkSystem, "1");
        return getTree(list, "0");
    }

    private List<SysMenuTree> getTree(List<SysMenu> list, String pid){
        List<SysMenuTree> treeList = new ArrayList<>();
        List<SysMenu> l = list.stream().filter(o->o.getPid().equals(pid)).collect(Collectors.toList());
        l.sort(new Comparator<SysMenu>() {
            @Override
            public int compare(SysMenu o1, SysMenu o2) {
                if(o1.getSort() > o2.getSort()){
                    return 1;
                }
                else if(o1.getSort() < o2.getSort()) {
                    return -1;
                }
                else  {
                    return 0;
                }
            }
        });
        for (SysMenu m: l ) {
            SysMenuTree tree = new SysMenuTree();
            tree.setId(m.getId());
            tree.setTitle(m.getName());
            tree.setSpread(false);
            tree.setHref(m.getUrl());
            tree.setPid(m.getPid());
            tree.setFkSystem(m.getFkSystem());
            List<SysMenuTree> children = getTree(list, m.getId());
            tree.setChildren(children);
            treeList.add(tree);
        }
        return treeList;
    }
}
